package com.example.endusation.neo4j;

import org.neo4j.driver.Driver;
import org.neo4j.driver.Result;
import org.neo4j.driver.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Repository
public class DiscreteMathRepository {

    private final Driver neo4jDriver;

    @Autowired
    public DiscreteMathRepository(Driver neo4jDriver) {
        this.neo4jDriver = neo4jDriver;
    }

    /**
     * 查询与问题相关的概念和定理
     */
    public List<String> queryKnowledgeGraph(String question) {
        List<String> results = new ArrayList<>();

        // 提取问题中的关键词（实际应用中可使用NLP工具优化）
        List<String> keywords = extractKeywords(question);

        try (Session session = neo4jDriver.session()) {
            for (String keyword : keywords) {
                // 查询包含关键词的概念节点
                String cypher = "MATCH (n:Concept) WHERE n.name CONTAINS $keyword " +
                        "OPTIONAL MATCH (n)-[r]->(m) " +
                        "RETURN n.name AS concept, n.definition AS definition, " +
                        "type(r) AS relation, m.name AS relatedConcept";

                Result result = session.run(cypher, Map.of("keyword", keyword));

                // 修复：通过stream()获取流后再调用forEach
                result.stream().forEach(record -> {
                    StringBuilder sb = new StringBuilder();
                    sb.append("概念: ").append(record.get("concept").asString());
                    if (!record.get("definition").isNull()) {
                        sb.append("，定义: ").append(record.get("definition").asString());
                    }
                    if (!record.get("relation").isNull()) {
                        sb.append("，与").append(record.get("relatedConcept").asString())
                                .append("是").append(record.get("relation").asString()).append("关系");
                    }
                    results.add(sb.toString());
                });

                // 查询相关定理
                String theoremCypher = "MATCH (t:Theorem) WHERE t.name CONTAINS $keyword OR t.content CONTAINS $keyword " +
                        "RETURN t.name AS name, t.content AS content";

                Result theoremResult = session.run(theoremCypher, Map.of("keyword", keyword));

                // 修复：同样通过stream()获取流后再调用forEach
                theoremResult.stream().forEach(record -> {
                    results.add("定理: " + record.get("name").asString() + "，内容: " + record.get("content").asString());
                });
            }
        }

        return results;
    }


    /**
     * 简单关键词提取（实际应用中可集成HanLP等工具）
     */
    private List<String> extractKeywords(String question) {
        // 离散数学领域关键词库
        List<String> domainKeywords = List.of(
                "集合", "关系", "函数", "图论", "树", "路径",
                "回路", "矩阵", "群", "环", "域", "逻辑",
                "命题", "谓词", "推理", "等价", "同构", "基数"
        );

        List<String> extracted = new ArrayList<>();
        for (String kw : domainKeywords) {
            if (question.contains(kw)) {
                extracted.add(kw);
            }
        }
        return extracted;
    }
}
